/*
 * @(#)org.example 2020/3/25/0025
 *
 * Copy Right@ 人人译视界
 */


package org.example;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * <pre>
 * @author tuwei
 *
 * @version 0.9
 *
 * 修改版本: 0.9
 * 修改日期: 2020/3/25/0025
 * 修改人 :  tuwei
 * 修改说明: 初步完成
 * 复审人 ：
 * </pre>
 */
public class NioServer {
	public static void main(String[] args) throws IOException {
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		serverSocketChannel.socket().bind(new InetSocketAddress(8000));
		serverSocketChannel.configureBlocking(false);

		Selector selector = Selector.open();
		serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

		while(true) {
			if (selector.select(1000) == 0) {
				System.out.println("服务器等待了1s，无连接");
				continue;
			}
			// 返回关注事件的集合
			Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
			while (keyIterator.hasNext()) {
				SelectionKey sk = keyIterator.next();
				if (sk.isAcceptable()) {
					// 有新的客户端连接，创建channel
					SocketChannel channel = serverSocketChannel.accept();
					channel.configureBlocking(false);
					// 将channel注册到selector，关注事件为OP_READ，同时给channel关联一个buffer
					channel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
				}
				if (sk.isReadable()) {
					// 通道中发生的是读事件
					SocketChannel channel = (SocketChannel) sk.channel();
					// 获取该channel关联的buffer
					ByteBuffer buffer = (ByteBuffer) sk.attachment();
					channel.read(buffer);
					System.out.println("从客户端传来：" + new String(buffer.array()));
				}
				keyIterator.remove();
			}
		}
	}
}
